home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / plistlib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  18.7 KB  |  535 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''plistlib.py -- a tool to generate and parse MacOSX .plist files.
  5.  
  6. The PropertyList (.plist) file format is a simple XML pickle supporting
  7. basic object types, like dictionaries, lists, numbers and strings.
  8. Usually the top level object is a dictionary.
  9.  
  10. To write out a plist file, use the writePlist(rootObject, pathOrFile)
  11. function. \'rootObject\' is the top level object, \'pathOrFile\' is a
  12. filename or a (writable) file object.
  13.  
  14. To parse a plist from a file, use the readPlist(pathOrFile) function,
  15. with a file name or a (readable) file object as the only argument. It
  16. returns the top level object (again, usually a dictionary).
  17.  
  18. To work with plist data in strings, you can use readPlistFromString()
  19. and writePlistToString().
  20.  
  21. Values can be strings, integers, floats, booleans, tuples, lists,
  22. dictionaries, Data or datetime.datetime objects. String values (including
  23. dictionary keys) may be unicode strings -- they will be written out as
  24. UTF-8.
  25.  
  26. The <data> plist type is supported through the Data class. This is a
  27. thin wrapper around a Python string.
  28.  
  29. Generate Plist example:
  30.  
  31.     pl = dict(
  32.         aString="Doodah",
  33.         aList=["A", "B", 12, 32.1, [1, 2, 3]],
  34.         aFloat=0.1,
  35.         anInt=728,
  36.         aDict=dict(
  37.             anotherString="<hello & hi there!>",
  38.             aUnicodeValue=u\'M\\xe4ssig, Ma\\xdf\',
  39.             aTrueValue=True,
  40.             aFalseValue=False,
  41.         ),
  42.         someData=Data("<binary gunk>"),
  43.         someMoreData=Data("<lots of binary gunk>" * 10),
  44.         aDate=datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
  45.     )
  46.     # unicode keys are possible, but a little awkward to use:
  47.     pl[u\'\\xc5benraa\'] = "That was a unicode key."
  48.     writePlist(pl, fileName)
  49.  
  50. Parse Plist example:
  51.  
  52.     pl = readPlist(pathOrFile)
  53.     print pl["aKey"]
  54. '''
  55. __all__ = [
  56.     'readPlist',
  57.     'writePlist',
  58.     'readPlistFromString',
  59.     'writePlistToString',
  60.     'readPlistFromResource',
  61.     'writePlistToResource',
  62.     'Plist',
  63.     'Data',
  64.     'Dict']
  65. import binascii
  66. import datetime
  67. from cStringIO import StringIO
  68. import re
  69. import warnings
  70.  
  71. def readPlist(pathOrFile):
  72.     """Read a .plist file. 'pathOrFile' may either be a file name or a
  73.     (readable) file object. Return the unpacked root object (which
  74.     usually is a dictionary).
  75.     """
  76.     didOpen = 0
  77.     if isinstance(pathOrFile, (str, unicode)):
  78.         pathOrFile = open(pathOrFile)
  79.         didOpen = 1
  80.     
  81.     p = PlistParser()
  82.     rootObject = p.parse(pathOrFile)
  83.     if didOpen:
  84.         pathOrFile.close()
  85.     
  86.     return rootObject
  87.  
  88.  
  89. def writePlist(rootObject, pathOrFile):
  90.     """Write 'rootObject' to a .plist file. 'pathOrFile' may either be a
  91.     file name or a (writable) file object.
  92.     """
  93.     didOpen = 0
  94.     if isinstance(pathOrFile, (str, unicode)):
  95.         pathOrFile = open(pathOrFile, 'w')
  96.         didOpen = 1
  97.     
  98.     writer = PlistWriter(pathOrFile)
  99.     writer.writeln('<plist version="1.0">')
  100.     writer.writeValue(rootObject)
  101.     writer.writeln('</plist>')
  102.     if didOpen:
  103.         pathOrFile.close()
  104.     
  105.  
  106.  
  107. def readPlistFromString(data):
  108.     '''Read a plist data from a string. Return the root object.
  109.     '''
  110.     return readPlist(StringIO(data))
  111.  
  112.  
  113. def writePlistToString(rootObject):
  114.     """Return 'rootObject' as a plist-formatted string.
  115.     """
  116.     f = StringIO()
  117.     writePlist(rootObject, f)
  118.     return f.getvalue()
  119.  
  120.  
  121. def readPlistFromResource(path, restype = 'plst', resid = 0):
  122.     '''Read plst resource from the resource fork of path.
  123.     '''
  124.     warnings.warnpy3k('In 3.x, readPlistFromResource is removed.')
  125.     FSRef = FSRef
  126.     FSGetResourceForkName = FSGetResourceForkName
  127.     import Carbon.File
  128.     fsRdPerm = fsRdPerm
  129.     import Carbon.Files
  130.     Res = Res
  131.     import Carbon
  132.     fsRef = FSRef(path)
  133.     resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm)
  134.     Res.UseResFile(resNum)
  135.     plistData = Res.Get1Resource(restype, resid).data
  136.     Res.CloseResFile(resNum)
  137.     return readPlistFromString(plistData)
  138.  
  139.  
  140. def writePlistToResource(rootObject, path, restype = 'plst', resid = 0):
  141.     """Write 'rootObject' as a plst resource to the resource fork of path.
  142.     """
  143.     warnings.warnpy3k('In 3.x, writePlistToResource is removed.')
  144.     FSRef = FSRef
  145.     FSGetResourceForkName = FSGetResourceForkName
  146.     import Carbon.File
  147.     fsRdWrPerm = fsRdWrPerm
  148.     import Carbon.Files
  149.     Res = Res
  150.     import Carbon
  151.     plistData = writePlistToString(rootObject)
  152.     fsRef = FSRef(path)
  153.     resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm)
  154.     Res.UseResFile(resNum)
  155.     
  156.     try:
  157.         Res.Get1Resource(restype, resid).RemoveResource()
  158.     except Res.Error:
  159.         pass
  160.  
  161.     res = Res.Resource(plistData)
  162.     res.AddResource(restype, resid, '')
  163.     res.WriteResource()
  164.     Res.CloseResFile(resNum)
  165.  
  166.  
  167. class DumbXMLWriter:
  168.     
  169.     def __init__(self, file, indentLevel = 0, indent = '\t'):
  170.         self.file = file
  171.         self.stack = []
  172.         self.indentLevel = indentLevel
  173.         self.indent = indent
  174.  
  175.     
  176.     def beginElement(self, element):
  177.         self.stack.append(element)
  178.         self.writeln('<%s>' % element)
  179.         self.indentLevel += 1
  180.  
  181.     
  182.     def endElement(self, element):
  183.         if not self.indentLevel > 0:
  184.             raise AssertionError
  185.         if not self.stack.pop() == element:
  186.             raise AssertionError
  187.         self.indentLevel -= 1
  188.         self.writeln('</%s>' % element)
  189.  
  190.     
  191.     def simpleElement(self, element, value = None):
  192.         if value is not None:
  193.             value = _escapeAndEncode(value)
  194.             self.writeln('<%s>%s</%s>' % (element, value, element))
  195.         else:
  196.             self.writeln('<%s/>' % element)
  197.  
  198.     
  199.     def writeln(self, line):
  200.         if line:
  201.             self.file.write(self.indentLevel * self.indent + line + '\n')
  202.         else:
  203.             self.file.write('\n')
  204.  
  205.  
  206. _dateParser = re.compile('(?P<year>\\d\\d\\d\\d)(?:-(?P<month>\\d\\d)(?:-(?P<day>\\d\\d)(?:T(?P<hour>\\d\\d)(?::(?P<minute>\\d\\d)(?::(?P<second>\\d\\d))?)?)?)?)?Z')
  207.  
  208. def _dateFromString(s):
  209.     order = ('year', 'month', 'day', 'hour', 'minute', 'second')
  210.     gd = _dateParser.match(s).groupdict()
  211.     lst = []
  212.     for key in order:
  213.         val = gd[key]
  214.         if val is None:
  215.             break
  216.         
  217.         lst.append(int(val))
  218.     
  219.     return datetime.datetime(*lst)
  220.  
  221.  
  222. def _dateToString(d):
  223.     return '%04d-%02d-%02dT%02d:%02d:%02dZ' % (d.year, d.month, d.day, d.hour, d.minute, d.second)
  224.  
  225. _controlCharPat = re.compile('[\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x0b\\x0c\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f]')
  226.  
  227. def _escapeAndEncode(text):
  228.     m = _controlCharPat.search(text)
  229.     if m is not None:
  230.         raise ValueError("strings can't contains control characters; use plistlib.Data instead")
  231.     m is not None
  232.     text = text.replace('\r\n', '\n')
  233.     text = text.replace('\r', '\n')
  234.     text = text.replace('&', '&')
  235.     text = text.replace('<', '<')
  236.     text = text.replace('>', '>')
  237.     return text.encode('utf-8')
  238.  
  239. PLISTHEADER = '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
  240.  
  241. class PlistWriter(DumbXMLWriter):
  242.     
  243.     def __init__(self, file, indentLevel = 0, indent = '\t', writeHeader = 1):
  244.         if writeHeader:
  245.             file.write(PLISTHEADER)
  246.         
  247.         DumbXMLWriter.__init__(self, file, indentLevel, indent)
  248.  
  249.     
  250.     def writeValue(self, value):
  251.         if isinstance(value, (str, unicode)):
  252.             self.simpleElement('string', value)
  253.         elif isinstance(value, bool):
  254.             if value:
  255.                 self.simpleElement('true')
  256.             else:
  257.                 self.simpleElement('false')
  258.         elif isinstance(value, (int, long)):
  259.             self.simpleElement('integer', '%d' % value)
  260.         elif isinstance(value, float):
  261.             self.simpleElement('real', repr(value))
  262.         elif isinstance(value, dict):
  263.             self.writeDict(value)
  264.         elif isinstance(value, Data):
  265.             self.writeData(value)
  266.         elif isinstance(value, datetime.datetime):
  267.             self.simpleElement('date', _dateToString(value))
  268.         elif isinstance(value, (tuple, list)):
  269.             self.writeArray(value)
  270.         else:
  271.             raise TypeError('unsuported type: %s' % type(value))
  272.         return isinstance(value, (str, unicode))
  273.  
  274.     
  275.     def writeData(self, data):
  276.         self.beginElement('data')
  277.         self.indentLevel -= 1
  278.         maxlinelength = 76 - len(self.indent.replace('\t', '        ') * self.indentLevel)
  279.         for line in data.asBase64(maxlinelength).split('\n'):
  280.             if line:
  281.                 self.writeln(line)
  282.                 continue
  283.             self
  284.         
  285.         self.indentLevel += 1
  286.         self.endElement('data')
  287.  
  288.     
  289.     def writeDict(self, d):
  290.         self.beginElement('dict')
  291.         items = d.items()
  292.         items.sort()
  293.         for key, value in items:
  294.             if not isinstance(key, (str, unicode)):
  295.                 raise TypeError('keys must be strings')
  296.             isinstance(key, (str, unicode))
  297.             self.simpleElement('key', key)
  298.             self.writeValue(value)
  299.         
  300.         self.endElement('dict')
  301.  
  302.     
  303.     def writeArray(self, array):
  304.         self.beginElement('array')
  305.         for value in array:
  306.             self.writeValue(value)
  307.         
  308.         self.endElement('array')
  309.  
  310.  
  311.  
  312. class _InternalDict(dict):
  313.     
  314.     def __getattr__(self, attr):
  315.         
  316.         try:
  317.             value = self[attr]
  318.         except KeyError:
  319.             raise AttributeError, attr
  320.  
  321.         warn = warn
  322.         import warnings
  323.         warn('Attribute access from plist dicts is deprecated, use d[key] notation instead', PendingDeprecationWarning)
  324.         return value
  325.  
  326.     
  327.     def __setattr__(self, attr, value):
  328.         warn = warn
  329.         import warnings
  330.         warn('Attribute access from plist dicts is deprecated, use d[key] notation instead', PendingDeprecationWarning)
  331.         self[attr] = value
  332.  
  333.     
  334.     def __delattr__(self, attr):
  335.         
  336.         try:
  337.             del self[attr]
  338.         except KeyError:
  339.             raise AttributeError, attr
  340.  
  341.         warn = warn
  342.         import warnings
  343.         warn('Attribute access from plist dicts is deprecated, use d[key] notation instead', PendingDeprecationWarning)
  344.  
  345.  
  346.  
  347. class Dict(_InternalDict):
  348.     
  349.     def __init__(self, **kwargs):
  350.         warn = warn
  351.         import warnings
  352.         warn('The plistlib.Dict class is deprecated, use builtin dict instead', PendingDeprecationWarning)
  353.         super(Dict, self).__init__(**kwargs)
  354.  
  355.  
  356.  
  357. class Plist(_InternalDict):
  358.     '''This class has been deprecated. Use readPlist() and writePlist()
  359.     functions instead, together with regular dict objects.
  360.     '''
  361.     
  362.     def __init__(self, **kwargs):
  363.         warn = warn
  364.         import warnings
  365.         warn('The Plist class is deprecated, use the readPlist() and writePlist() functions instead', PendingDeprecationWarning)
  366.         super(Plist, self).__init__(**kwargs)
  367.  
  368.     
  369.     def fromFile(cls, pathOrFile):
  370.         '''Deprecated. Use the readPlist() function instead.'''
  371.         rootObject = readPlist(pathOrFile)
  372.         plist = cls()
  373.         plist.update(rootObject)
  374.         return plist
  375.  
  376.     fromFile = classmethod(fromFile)
  377.     
  378.     def write(self, pathOrFile):
  379.         '''Deprecated. Use the writePlist() function instead.'''
  380.         writePlist(self, pathOrFile)
  381.  
  382.  
  383.  
  384. def _encodeBase64(s, maxlinelength = 76):
  385.     maxbinsize = (maxlinelength // 4) * 3
  386.     pieces = []
  387.     for i in range(0, len(s), maxbinsize):
  388.         chunk = s[i:i + maxbinsize]
  389.         pieces.append(binascii.b2a_base64(chunk))
  390.     
  391.     return ''.join(pieces)
  392.  
  393.  
  394. class Data:
  395.     '''Wrapper for binary data.'''
  396.     
  397.     def __init__(self, data):
  398.         self.data = data
  399.  
  400.     
  401.     def fromBase64(cls, data):
  402.         return cls(binascii.a2b_base64(data))
  403.  
  404.     fromBase64 = classmethod(fromBase64)
  405.     
  406.     def asBase64(self, maxlinelength = 76):
  407.         return _encodeBase64(self.data, maxlinelength)
  408.  
  409.     
  410.     def __cmp__(self, other):
  411.         if isinstance(other, self.__class__):
  412.             return cmp(self.data, other.data)
  413.         if isinstance(other, str):
  414.             return cmp(self.data, other)
  415.         return cmp(id(self), id(other))
  416.  
  417.     
  418.     def __repr__(self):
  419.         return '%s(%s)' % (self.__class__.__name__, repr(self.data))
  420.  
  421.  
  422.  
  423. class PlistParser:
  424.     
  425.     def __init__(self):
  426.         self.stack = []
  427.         self.currentKey = None
  428.         self.root = None
  429.  
  430.     
  431.     def parse(self, fileobj):
  432.         ParserCreate = ParserCreate
  433.         import xml.parsers.expat
  434.         parser = ParserCreate()
  435.         parser.StartElementHandler = self.handleBeginElement
  436.         parser.EndElementHandler = self.handleEndElement
  437.         parser.CharacterDataHandler = self.handleData
  438.         parser.ParseFile(fileobj)
  439.         return self.root
  440.  
  441.     
  442.     def handleBeginElement(self, element, attrs):
  443.         self.data = []
  444.         handler = getattr(self, 'begin_' + element, None)
  445.         if handler is not None:
  446.             handler(attrs)
  447.         
  448.  
  449.     
  450.     def handleEndElement(self, element):
  451.         handler = getattr(self, 'end_' + element, None)
  452.         if handler is not None:
  453.             handler()
  454.         
  455.  
  456.     
  457.     def handleData(self, data):
  458.         self.data.append(data)
  459.  
  460.     
  461.     def addObject(self, value):
  462.         if self.currentKey is not None:
  463.             self.stack[-1][self.currentKey] = value
  464.             self.currentKey = None
  465.         elif not self.stack:
  466.             self.root = value
  467.         else:
  468.             self.stack[-1].append(value)
  469.  
  470.     
  471.     def getData(self):
  472.         data = ''.join(self.data)
  473.         
  474.         try:
  475.             data = data.encode('ascii')
  476.         except UnicodeError:
  477.             pass
  478.  
  479.         self.data = []
  480.         return data
  481.  
  482.     
  483.     def begin_dict(self, attrs):
  484.         d = _InternalDict()
  485.         self.addObject(d)
  486.         self.stack.append(d)
  487.  
  488.     
  489.     def end_dict(self):
  490.         self.stack.pop()
  491.  
  492.     
  493.     def end_key(self):
  494.         self.currentKey = self.getData()
  495.  
  496.     
  497.     def begin_array(self, attrs):
  498.         a = []
  499.         self.addObject(a)
  500.         self.stack.append(a)
  501.  
  502.     
  503.     def end_array(self):
  504.         self.stack.pop()
  505.  
  506.     
  507.     def end_true(self):
  508.         self.addObject(True)
  509.  
  510.     
  511.     def end_false(self):
  512.         self.addObject(False)
  513.  
  514.     
  515.     def end_integer(self):
  516.         self.addObject(int(self.getData()))
  517.  
  518.     
  519.     def end_real(self):
  520.         self.addObject(float(self.getData()))
  521.  
  522.     
  523.     def end_string(self):
  524.         self.addObject(self.getData())
  525.  
  526.     
  527.     def end_data(self):
  528.         self.addObject(Data.fromBase64(self.getData()))
  529.  
  530.     
  531.     def end_date(self):
  532.         self.addObject(_dateFromString(self.getData()))
  533.  
  534.  
  535.